import java.util.*;

/**
 * JSMsgProtocolClient - The client protocol for Jam Session
 * 
 * @author James Varvaro
 */
public class JSMsgProtocolClient {
    JSClient client;
    
    public JSMsgProtocolClient(JSClient aClient) {
        this.client = aClient;
    }
    
    public void process(String msg) throws Exception{
        StringTokenizer tokens = new StringTokenizer(msg);
        // Retrieve message type {CONNECTION, NOTE, or CHANGE}
        if(tokens.countTokens() > 3) {
            String msgType = tokens.nextToken();
            String userid = tokens.nextToken();
            String username = tokens.nextToken();
            if(msgType.equals("NOTE")) {
                // Extract note info
                String noteid = tokens.nextToken();
                String instrumentType = tokens.nextToken();
                String pitch = tokens.nextToken();
                String noteStatus = tokens.nextToken();
                
                if(noteStatus.equals("true")) {
                    // Begin playing a note.
                    client.startNote(Integer.parseInt(noteid),
                                        instrumentType,
                                        Integer.parseInt(pitch),
                                        noteStatus);
                }
                else if(noteStatus.equals("false")) {
                    // End a note
                    client.endNote(Integer.parseInt(noteid),
                                        instrumentType,
                                        Integer.parseInt(pitch),
                                        noteStatus);
                }
                
            }
            else if(msgType.equals("CHANGE")) {
            }
            else if(msgType.equals("CONNECTION")) {
                String connectionType = tokens.nextToken();
                String connectionStatus = tokens.nextToken();
                if(connectionType.equals("notify")) {
                    if(connectionStatus.equals("true")) {
                        // client connection info
                        if(!client.isUserInit()) {
                            client.initUser(Integer.parseInt(userid), username, "piano");
                            System.out.println(username + " has been assigned an id of: " + Integer.parseInt(userid));
                        }
                    }
                    else if(connectionStatus.equals("false")) {
                        // disconnect client
                    }
                    else {
                        System.out.println("Not a valid connection status.");
                    }
                }
            }
            else {
                System.out.println("Invalid msg from server.");
            }
        }
        else {
            System.out.println("invalid message: not enough tokens: " + msg);
        }
    }
}
